package com.koron.housing.util;

import cn.hutool.extra.spring.SpringUtil;
import com.koron.common.task.web.entity.CronTask;
import com.koron.common.task.web.service.XxlJobService;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.Calendar;
import java.util.Date;

/**
 * @author jzp
 * @since 2022/4/6
 */
@Slf4j
public class DelayUtils {

    /**
     * 创建延时任务
     * @param bizId 业务id
     * @param timeStamp 时间戳，何时执行
     * @param mark 数据源标识
     * @param xxlJobVal 注解的value值
     */
    public static void putTask(String bizId, Long timeStamp, String mark, String xxlJobVal) {
        XxlJobService xxlJobService = SpringUtil.getBean(XxlJobService.class);
        Assert.notNull(xxlJobService, "未找到XxlJobService");
        CronTask cronTask = xxlJobService.getCronTaskById(bizId);
        String jobName = "通知任务：";
        String username = "admin";
        if (cronTask != null) {
            // 更新任务
            log.info("更新：{}", bizId);
            xxlJobService.update(bizId, genCronStr(new Date(timeStamp)), cronTask.getMark(), jobName + xxlJobVal, username, xxlJobVal);
            if (cronTask.getStatus() == 0) {
                xxlJobService.start(bizId);
            }
        } else {
            log.info("创建：{}", bizId);
            xxlJobService.addSimpleJob(bizId, genCronStr(new Date(timeStamp)), mark, jobName, username, xxlJobVal, 10);
            xxlJobService.start(bizId);
        }

    }

    public static void removeTask(String bizId) {
        XxlJobService xxlJobService = SpringUtil.getBean(XxlJobService.class);
        Assert.notNull(xxlJobService, "未找到XxlJobService");
        xxlJobService.remove(bizId);
    }

    private static String genCronStr(Date date) {
        //秒 分钟 小时 日 月 星期 年
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return "0 " +
                cal.get(Calendar.MINUTE) + " " +
                cal.get(Calendar.HOUR_OF_DAY) + " " +
                cal.get(Calendar.DAY_OF_MONTH) + " " +
                (cal.get(Calendar.MONTH) + 1) + " " +
                "? " +
                cal.get(Calendar.YEAR);
    }

    public static String getCurrBusinessId() {
        return getCurrTask().getBusinessId();
    }

    public static CronTask getCurrTask() {
        XxlJobService xxlJobService = SpringUtil.getBean(XxlJobService.class);
        return xxlJobService.getCronTaskByXxlJobId((int) XxlJobHelper.getJobId());
    }

}
